package com.itheima.health.config;

import com.itheima.health.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(JwtProperties.class)
public class SpringBootSecurityService extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtProperties properties;
    //重写用户认证信息模板：
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //   认证管理器对象  配置用户认证信息
//        数据库版用户认证
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//       auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");

    }

    /**
     *   重写 登录  前端一般采用 ajax请求提交用户数据
     *    配置过滤器完成用户认证和授权
     *    以token形式返回
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable().
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session
    }

//    直接采用@Bean方式 创建该对象 即可
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();//  密码加密 对象
    }

    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("1234");
        System.out.println("password = " + encode);
    }

}